<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频数据分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts-wordcloud/2.0.0/echarts-wordcloud.min.js"></script>
    <script>tailwind.config = {
        theme: {
            extend: {
                colors: {
                    bilibili: {
                        pink: '#FB7299',
                        blue: '#23ADE5',
                        dark: '#18191C',
                    }
                },
                fontFamily: {
                    sans: ['"HarmonyOS Sans"', 'sans-serif'],
                }
            }
        }
    }
    </script>
    <style>        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

    body {
        font-family: 'Noto Sans SC', sans-serif;
        background-color: #f5f5f5;
    }

    .gradient-bg {
        background: linear-gradient(135deg, #23ADE5 0%, #FB7299 100%);
    }

    .card-hover {
        transition: all 0.3s ease;
    }

    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }

    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }

    .card-hover:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    }

    .progress-bar {
        height: 6px;
        border-radius: 3px;
        background-color: #e5e7eb;
        overflow: hidden;
    }

    .progress-fill {
        height: 100%;
        border-radius: 3px;
        background: linear-gradient(90deg, #FB7299, #23ADE5);
    }

    .word-cloud {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        padding: 20px;
        min-height: 300px;
    }

    .level-badge {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        border-radius: 50%;
        color: white;
        font-size: 12px;
        font-weight: bold;
        margin-right: 5px;
    }

    .level-0 { background-color: #e5e7eb; }
    .level-1 { background-color: #cccccc; }
    .level-2 { background-color: #99cc66; }
    .level-3 { background-color: #3399ff; }
    .level-4 { background-color: #9966cc; }
    .level-5 { background-color: #ff9900; }
    .level-6 { background-color: #ff6666; }

    .chart-container {
        width: 100%;
        height: 400px;
    }

    .loading-spinner {
        border: 4px solid rgba(0, 0, 0, 0.1);
        border-radius: 50%;
        border-top: 4px solid #FB7299;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 20px auto;
    }

    /* 新增样式 */
    .hover-effect {
        transition: all 0.2s ease;
        cursor: pointer;
    }
    .hover-effect:hover {
        transform: translateY(-2px);
        opacity: 0.9;
    }
    .tag-hover {
        transition: all 0.2s ease;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    </style>
</head>
<body class="bg-gray-100">
<div class="min-h-screen">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center cursor-pointer hover:opacity-80 transition-opacity duration-200"
                         onclick="window.location.href = 'main'"
                         title="返回主页">
                        <i class="fab fa-bilibili text-3xl text-bilibili-pink hover:scale-105 transition-transform"></i>
                        <span class="ml-2 text-xl font-bold text-gray-800 hover:text-bilibili-pink transition-colors">视频数据分析</span>
                    </div>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div class="bg-white rounded-xl shadow-md overflow-hidden mb-8">
            <div class="p-6">
                <div class="flex flex-col gap-6">
                    <div class="flex flex-col md:flex-row justify-between items-start">
                        <div class="flex-1">
                            <h1 id="videoTitle" class="text-2xl font-bold text-gray-800 mb-2">加载中...</h1>
                            <p id="videoDesc" class="text-gray-600 mb-4">加载视频描述...</p>

                            <div class="flex flex-wrap items-center text-sm text-gray-500 mb-4 gap-4">
                                <span><i class="fas fa-calendar-alt mr-1"></i> 上传时间: <span id="uploadTime">加载中...</span></span>
                                <span><i class="fas fa-clock mr-1"></i> 视频时长: <span id="videoDuration">加载中...</span></span>
                            </div>

                            <div id="videoTags" class="flex flex-wrap gap-2 mb-4">
                                <span class="bg-gray-100 px-3 py-1 rounded-full text-sm">加载标签...</span>
                            </div>

                            <div class="flex items-center hover-effect">
                                <div>
                                    <p id="upName" class="font-medium hover:text-bilibili-pink">UP主名称</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex flex-col gap-2 mt-4 md:mt-0">
                            <button id="videoLinkBtn" class="bg-bilibili-pink hover:bg-bilibili-blue text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                                <i class="fas fa-external-link-alt mr-2"></i>
                                观看视频
                            </button>
                            <button onclick="window.location.href=`comment?bvid=${bvid}`" class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                                <i class="fas fa-comments mr-2"></i>
                                查看评论
                            </button>
                            <button onclick="window.location.href=`danmu?bvid=${bvid}`" class="bg-purple-500 hover:bg-purple-600 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                                <i class="fas fa-comment-dots mr-2"></i>
                                查看弹幕
                            </button>
                            <button onclick="updateVideoData()" class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                                <i class="fas fa-sync-alt mr-2"></i>
                                更新数据
                            </button>
                        </div>
                    </div>
                </div>
                <div id="basicInfoError" class="mt-4"></div>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-blue-100 text-bilibili-blue">
                            <i class="fas fa-play-circle text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">播放量</p>
                            <p id="viewCount" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="viewProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-green-100 text-green-600">
                            <i class="fas fa-comments text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">评论量</p>
                            <p id="replyCount" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="replyProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-purple-100 text-purple-600">
                            <i class="fas fa-comment-dots text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">弹幕量</p>
                            <p id="danmakuCount" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="danmakuProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-blue-100 text-blue-500">
                            <i class="fas fa-share-alt text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">分享量</p>
                            <p id="shareCount" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                    <div class="progress-bar mt-4">
                        <div id="shareProgress" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">观众性别分布</h2>
                    <div class="flex justify-center">
                        <div id="genderChart" class="w-48 h-48"></div>
                    </div>
                    <div class="mt-6 flex justify-center space-x-8">
                        <div class="flex items-center">
                            <div class="w-3 h-3 rounded-full bg-bilibili-blue mr-2"></div>
                            <span id="malePercent" class="text-sm text-gray-600">男性: 加载中...</span>
                        </div>
                        <div class="flex items-center">
                            <div class="w-3 h-3 rounded-full bg-bilibili-pink mr-2"></div>
                            <span id="femalePercent" class="text-sm text-gray-600">女性: 加载中...</span>
                        </div>
                        <div class="flex items-center">
                            <div class="w-3 h-3 rounded-full bg-gray-500 mr-2"></div>
                            <span id="unknownPercent" class="text-sm text-gray-600">保密: 加载中...</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover lg:col-span-2">
                <div class="p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">观众等级分布</h2>
                    <div class="flex flex-wrap gap-4">
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level0Bar" class="absolute bottom-0 left-0 right-0 bg-bilibili-pink" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-1">0</span>
                                    <span class="text-sm font-medium">Lv0</span>
                                    <p id="level0Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level1Bar" class="absolute bottom-0 left-0 right-0 bg-bilibili-pink" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-1">1</span>
                                    <span class="text-sm font-medium">Lv1</span>
                                    <p id="level1Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level2Bar" class="absolute bottom-0 left-0 right-0 bg-bilibili-blue" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-2">2</span>
                                    <span class="text-sm font-medium">Lv2</span>
                                    <p id="level2Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level3Bar" class="absolute bottom-0 left-0 right-0 bg-purple-500" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-3">3</span>
                                    <span class="text-sm font-medium">Lv3</span>
                                    <p id="level3Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level4Bar" class="absolute bottom-0 left-0 right-0 bg-green-500" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-4">4</span>
                                    <span class="text-sm font-medium">Lv4</span>
                                    <p id="level4Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level5Bar" class="absolute bottom-0 left-0 right-0 bg-yellow-500" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-5">5</span>
                                    <span class="text-sm font-medium">Lv5</span>
                                    <p id="level5Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1 min-w-[120px]">
                            <div class="h-32 bg-gray-100 rounded-lg relative overflow-hidden">
                                <div id="level6Bar" class="absolute bottom-0 left-0 right-0 bg-red-500" style="height: 0%;"></div>
                                <div class="absolute top-1/2 left-0 right-0 text-center transform -translate-y-1/2">
                                    <span class="level-badge level-6">6</span>
                                    <span class="text-sm font-medium">Lv6</span>
                                    <p id="level6Percent" class="text-xl font-bold">0%</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">弹幕词云</h2>
                    <div id="danmuWordCloud" class="chart-container">
                        <div class="loading-spinner"></div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">评论词云</h2>
                    <div id="commentWordCloud" class="chart-container">
                        <div class="loading-spinner"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">互动数据</h2>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-gray-600">点赞量</span>
                            <i class="fas fa-heart text-bilibili-pink"></i>
                        </div>
                        <p id="likeCount" class="text-2xl font-bold">加载中...</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-gray-600">投币量</span>
                            <i class="fas fa-coins text-yellow-500"></i>
                        </div>
                        <p id="coinCount" class="text-2xl font-bold">加载中...</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-gray-600">收藏量</span>
                            <i class="fas fa-star text-purple-500"></i>
                        </div>
                        <p id="favoriteCount" class="text-2xl font-bold">加载中...</p>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        <div class="flex items-center justify-between mb-2">
                            <span class="text-sm font-medium text-gray-600">三连量</span>
                            <i class="fas fa-trophy text-green-500"></i>
                        </div>
                        <p id="tripleCount" class="text-2xl font-bold">加载中...</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">视频数据分析结果</h2>
                <div id="analysisResult" class="bg-gray-50 p-4 rounded-lg">
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    const bvid = params.get('bvid');



    if (!bvid) {
        alert(`未获取到bv号，请确认是否已输入`);
        window.location.href = `main`;
    }

    async function updateVideoData() {
        const updateBtn = document.querySelector('button[onclick="updateVideoData()"]');
        const originalHTML = updateBtn.innerHTML; // 提前保存原始HTML

        try {
            updateBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>更新中...';
            updateBtn.disabled = true;

            const response = await fetch(`http://localhost:8080/v1/video/update/${bvid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const result = await response.json();

            if (result.code % 2 === 0) {
                await loadAllData();
                showToast('数据更新成功', 'success');
            } else {
                showToast(`更新失败: ${result.msg}`, 'error');
            }
        } catch (error) {
            console.error('更新数据失败:', error);
            showToast(`更新失败: ${error.message}`, 'error');
        } finally {
            updateBtn.innerHTML = originalHTML;
            updateBtn.disabled = false;
        }
    }

    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `fixed top-4 right-4 px-4 py-2 rounded-md shadow-md text-white ${
            type === 'success' ? 'bg-green-500' :
                type === 'error' ? 'bg-red-500' : 'bg-blue-500'
        } z-50 transition-all duration-300 transform translate-x-0 opacity-100`;
        toast.innerHTML = message;

        document.body.appendChild(toast);

        setTimeout(() => {
            toast.style.transform = 'translateX(100%)';
            toast.style.opacity = '0';
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 300);
        }, 3000);
    }

    async function fetchVideoData() {
        try {
            await fetch(`http://localhost:8080/v1/comment/query/${bvid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            let danmuWordCloud = [];
            try {
                const danmuWordCloudResponse = await fetch(`http://localhost:8080/v1/danmu/segmenter/${bvid}`, {
                    method: 'POST'
                });
                const danmuWordCloudData = await danmuWordCloudResponse.json();

                if (danmuWordCloudData.code % 2 === 0 && danmuWordCloudData.data) {
                    danmuWordCloud = Object.entries(danmuWordCloudData.data).map(([name, value]) => ({
                        name,
                        value: value * 100, // 放大值以便在词云中更好显示
                        originalValue: value // 保留原本的值
                    })).sort((a, b) => b.value - a.value).slice(0, 50); // 取前50个高频词
                } else {
                    console.error('获取弹幕词云数据失败:', danmuWordCloudData.msg);
                }
            } catch (error) {
                console.error('获取弹幕词云数据失败:', error);
            }

            let commentWordCloud = [];
            try {
                const commentWordCloudResponse = await fetch(`http://localhost:8080/v1/comment/segmenter/${bvid}`, {
                    method: 'POST'
                });
                const commentWordCloudData = await commentWordCloudResponse.json();

                if (commentWordCloudData.code % 2 === 0 && commentWordCloudData.data) {
                    commentWordCloud = Object.entries(commentWordCloudData.data).map(([name, value]) => ({
                        name,
                        value: value * 100, // 放大值以便在词云中更好显示
                        originalValue: value // 保留原本的值
                    })).sort((a, b) => b.value - a.value).slice(0, 50); // 取前50个高频词
                } else {
                    console.error('获取评论词云数据失败:', commentWordCloudData.msg);
                }
            } catch (error) {
                console.error('获取评论词云数据失败:', error);
            }

            const videoResponse = await fetch(`http://localhost:8080/v1/video/query/${bvid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const videoResult = await videoResponse.json();

            const genderResponse = await fetch(`http://localhost:8080/v1/comment/queryGender/${bvid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const genderResult = await genderResponse.json();

            const levelResponse = await fetch(`http://localhost:8080/v1/comment/queryLevel/${bvid}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const levelResult = await levelResponse.json();

            if (videoResult.code % 2 === 0) { // 成功
                const data = videoResult.data;

                let maleCount = 0, femaleCount = 0, unknownCount = 0;
                if (genderResult.code % 2 === 0 && genderResult.data) {
                    genderResult.data.forEach(item => {
                        if (item.gender === '男') maleCount = item.num;
                        else if (item.gender === '女') femaleCount = item.num;
                        else if (item.gender === '保密') unknownCount = item.num;
                    });
                }
                const totalGender = maleCount + femaleCount + unknownCount;
                const malePercent = totalGender > 0 ? Math.round((maleCount / totalGender) * 100) : 0;
                const femalePercent = totalGender > 0 ? Math.round((femaleCount / totalGender) * 100) : 0;
                const unknownPercent = totalGender > 0 ? Math.round((unknownCount / totalGender) * 100) : 0;

                const levelCounts = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
                if (levelResult.code % 2 === 0 && levelResult.data) {
                    levelResult.data.forEach(item => {
                        levelCounts[item.level] = item.num;
                    });
                }
                const totalLevel = Object.values(levelCounts).reduce((a, b) => a + b, 0);
                const levelPercents = {};
                for (let i = 0; i <= 6; i++) {
                    levelPercents[`lv${i}`] = totalLevel > 0 ? Math.round((levelCounts[i] / totalLevel) * 100) : 0;
                }

                const tripleCount = Math.min(
                    data.likeCount,
                    data.favoriteCount,
                    Math.floor(data.coinCount / 2)
                );

                return {
                    basicInfo: {
                        title: data.title,
                        desc: data.description,
                        uploadTime: new Date(data.uploadTime).toLocaleString(),
                        duration: data.duration,
                        tags: data.tags.split(','),
                        upInfo: {
                            name: data.username,
                            upUrl: `up?uid=${data.uid}`
                        },
                        videoUrl: `https://www.bilibili.com/video/${data.bv}`
                    },
                    wordCloud: {
                        danmu: danmuWordCloud.length > 0 ? danmuWordCloud : null,
                        comment: commentWordCloud.length > 0 ? commentWordCloud : null
                    },
                    stats: {
                        view: data.playCount,
                        reply: data.commentCount,
                        danmaku: data.damuCount,
                        share: data.shareCount,
                        like: data.likeCount,
                        coin: data.coinCount,
                        favorite: data.favoriteCount,
                        triple: tripleCount
                    },
                    audience: {
                        gender: {
                            male: malePercent,
                            female: femalePercent,
                            unknown: unknownPercent
                        },
                        level: {
                            lv0: levelPercents.lv0,
                            lv1: levelPercents.lv1,
                            lv2: levelPercents.lv2,
                            lv3: levelPercents.lv3,
                            lv4: levelPercents.lv4,
                            lv5: levelPercents.lv5,
                            lv6: levelPercents.lv6
                        }
                    },
                    analysis: [
                        `视频表现分析：该视频获得了${data.playCount}次播放，点赞率${(data.likeCount/data.playCount*100).toFixed(2)}%，收藏率${(data.favoriteCount/data.playCount*100).toFixed(2)}%。`,
                        "观众互动分析：弹幕和评论数据表明观众对视频内容有较高参与度。",
                        "关键词分析：弹幕和评论中出现频率最高的关键词是'支持'、'专业'和'干货'。",
                        "改进建议：可以考虑增加视频时长或制作系列内容，以进一步提高观众留存率。"
                    ]
                };
            } else { // 失败
                console.error('获取视频数据失败:', videoResult.msg, videoResult.data);
                return {
                    error: {
                        message: videoResult.msg,
                        detail: videoResult.data
                    }
                };
            }
        } catch (error) {
            console.error('请求视频数据失败:', error);
            return {
                error: {
                    message: '网络请求失败',
                    detail: error.message
                }
            };
        }
    }


    function formatNumber(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function initGenderChart(malePercent, femalePercent, unknownPercent) {
        try {
            const chart = echarts.init(document.getElementById('genderChart'));
            const option = {
                series: [{
                    type: 'pie',
                    radius: ['60%', '80%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: malePercent, name: '男性', itemStyle: { color: '#23ADE5' } },
                        { value: femalePercent, name: '女性', itemStyle: { color: '#FB7299' } },
                        { value: unknownPercent, name: '保密', itemStyle: { color: '#696969' } }
                    ]
                }]
            };
            chart.setOption(option);
            window.addEventListener('resize', function() {
                chart.resize();
            });
        } catch (error) {
            console.error('初始化性别图表失败:', error);
            document.getElementById('genderChart').innerHTML = `<div class="text-red-500">图表初始化失败: ${error.message}</div>`;
        }
    }


    function initDanmuWordCloud(data) {
        const container = document.getElementById('danmuWordCloud');
        if (!data || data.length === 0) {
            container.innerHTML = '<div class="text-gray-500 p-4 text-center">暂无弹幕词云数据</div>';
            return;
        }

        try {
            const chart = echarts.init(container);
            const option = {
                backgroundColor: '#ffffff',
                tooltip: {
                    show: true,
                    formatter: function (params) {
                        return `${params.name}: ${params.data.originalValue}`;
                    }
                },
                series: [{
                    type: 'wordCloud',
                    shape: 'circle',
                    left: 'center',
                    top: 'center',
                    width: '90%',
                    height: '90%',
                    right: null,
                    bottom: null,
                    sizeRange: [12, 60],
                    rotationRange: [-45, 45],
                    rotationStep: 15,
                    gridSize: 8,
                    drawOutOfBound: false,
                    textStyle: {
                        fontFamily: 'Noto Sans SC',
                        fontWeight: 'bold',
                        color: function () {
                            return 'rgb(' +
                                Math.round(Math.random() * 155 + 100) + ',' +
                                Math.round(Math.random() * 155 + 100) + ',' +
                                Math.round(Math.random() * 155 + 100) + ')';
                        }
                    },
                    emphasis: {
                        focus: 'self',
                        textStyle: {
                            shadowBlur: 10,
                            shadowColor: '#333'
                        }
                    },
                    data: data
                }]
            };
            chart.setOption(option);
            window.addEventListener('resize', function() {
                chart.resize();
            });
        } catch (error) {
            console.error('初始化弹幕词云失败:', error);
            container.innerHTML = `<div class="text-red-500">词云初始化失败: ${error.message}</div>`;
        }
    }

    function initCommentWordCloud(data) {
        const container = document.getElementById('commentWordCloud');
        if (!data || data.length === 0) {
            container.innerHTML = '<div class="text-gray-500 p-4 text-center">暂无评论词云数据</div>';
            return;
        }

        try {
            const chart = echarts.init(container);
            const option = {
                backgroundColor: '#ffffff',
                tooltip: {
                    show: true,
                    formatter: function (params) {
                        return `${params.name}: ${params.data.originalValue}`;
                    }
                },
                series: [{
                    type: 'wordCloud',
                    shape: 'circle',
                    left: 'center',
                    top: 'center',
                    width: '90%',
                    height: '90%',
                    right: null,
                    bottom: null,
                    sizeRange: [12, 60],
                    rotationRange: [-45, 45],
                    rotationStep: 15,
                    gridSize: 8,
                    drawOutOfBound: false,
                    textStyle: {
                        fontFamily: 'Noto Sans SC',
                        fontWeight: 'bold',
                        color: function () {
                            return 'rgb(' +
                                Math.round(Math.random() * 155 + 100) + ',' +
                                Math.round(Math.random() * 155 + 100) + ',' +
                                Math.round(Math.random() * 155 + 100) + ')';
                        }
                    },
                    emphasis: {
                        focus: 'self',
                        textStyle: {
                            shadowBlur: 10,
                            shadowColor: '#333'
                        }
                    },
                    data: data
                }]
            };
            chart.setOption(option);
            window.addEventListener('resize', function() {
                chart.resize();
            });
        } catch (error) {
            console.error('初始化评论词云失败:', error);
            container.innerHTML = `<div class="text-red-500">词云初始化失败: ${error.message}</div>`;
        }
    }


    async function loadAllData() {
        try {
            const data = await fetchVideoData();

            if (data.error) {
                document.getElementById('analysisResult').innerHTML = '';

                document.getElementById('basicInfoError').innerHTML =`
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4">
                    <p class="font-bold">${data.error.message}</p>
                    <p>${data.error.detail}</p>
                </div>
            `;
                return;
            }
            document.getElementById('basicInfoError').innerHTML = '';

            document.getElementById('videoTitle').textContent = data.basicInfo.title;
            document.getElementById('videoDesc').textContent = data.basicInfo.desc;
            document.getElementById('uploadTime').textContent = data.basicInfo.uploadTime;
            document.getElementById('videoDuration').textContent = data.basicInfo.duration;

            const tagsContainer = document.getElementById('videoTags');
            tagsContainer.innerHTML = '';
            data.basicInfo.tags.forEach(tag => {
                const tagElement = document.createElement('span');
                tagElement.className = 'bg-gray-100 px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-gray-200 transition-colors';
                tagElement.textContent = tag.trim();
                tagElement.addEventListener('click', () => {
                    const searchUrl = `https://search.bilibili.com/all?keyword=${encodeURIComponent(tag)}`;
                    window.open(searchUrl, '_blank');
                });
                tagsContainer.appendChild(tagElement);
            });

            document.getElementById('upName').textContent = data.basicInfo.upInfo.name;
            document.getElementById('videoLinkBtn').addEventListener('click', function() {
                window.open(data.basicInfo.videoUrl, '_blank');
            });
            document.getElementById('upName').addEventListener('click', function() {
                window.location.href = data.basicInfo.upInfo.upUrl;
            });

            document.getElementById('viewCount').textContent = formatNumber(data.stats.view);
            document.getElementById('likeCount').textContent = formatNumber(data.stats.like);
            document.getElementById('favoriteCount').textContent = formatNumber(data.stats.favorite);
            document.getElementById('danmakuCount').textContent = formatNumber(data.stats.danmaku);
            document.getElementById('coinCount').textContent = formatNumber(data.stats.coin);
            document.getElementById('shareCount').textContent = formatNumber(data.stats.share);
            document.getElementById('replyCount').textContent = formatNumber(data.stats.reply);
            document.getElementById('tripleCount').textContent = formatNumber(data.stats.triple);

            const maxStat = Math.max(data.stats.view, data.stats.reply, data.stats.danmaku, data.stats.share);
            const viewProgress = document.getElementById('viewProgress');
            const replyProgress = document.getElementById('replyProgress');
            const danmakuProgress = document.getElementById('danmakuProgress');
            const shareProgress = document.getElementById('shareProgress');
            if (viewProgress) viewProgress.style.width = `${(data.stats.view / maxStat) * 100}%`;
            if (replyProgress) replyProgress.style.width = `${(data.stats.reply / maxStat) * 100}%`;
            if (danmakuProgress) danmakuProgress.style.width = `${(data.stats.danmaku / maxStat) * 100}%`;
            if (shareProgress) shareProgress.style.width = `${(data.stats.share / maxStat) * 100}%`;

            document.getElementById('malePercent').textContent = `男性: ${data.audience.gender.male}%`;
            document.getElementById('femalePercent').textContent = `女性: ${data.audience.gender.female}%`;
            document.getElementById('unknownPercent').textContent = `保密: ${data.audience.gender.unknown}%`;
            initGenderChart(data.audience.gender.male, data.audience.gender.female, data.audience.gender.unknown);

            document.getElementById('level0Percent').textContent = `${data.audience.level.lv0}%`;
            document.getElementById('level1Percent').textContent = `${data.audience.level.lv1}%`;
            document.getElementById('level2Percent').textContent = `${data.audience.level.lv2}%`;
            document.getElementById('level3Percent').textContent = `${data.audience.level.lv3}%`;
            document.getElementById('level4Percent').textContent = `${data.audience.level.lv4}%`;
            document.getElementById('level5Percent').textContent = `${data.audience.level.lv5}%`;
            document.getElementById('level6Percent').textContent = `${data.audience.level.lv6}%`;

            document.getElementById('level0Bar').style.height = `${data.audience.level.lv0}%`;
            document.getElementById('level1Bar').style.height = `${data.audience.level.lv1}%`;
            document.getElementById('level2Bar').style.height = `${data.audience.level.lv2}%`;
            document.getElementById('level3Bar').style.height = `${data.audience.level.lv3}%`;
            document.getElementById('level4Bar').style.height = `${data.audience.level.lv4}%`;
            document.getElementById('level5Bar').style.height = `${data.audience.level.lv5}%`;
            document.getElementById('level6Bar').style.height = `${data.audience.level.lv6}%`;


            initDanmuWordCloud(data.wordCloud.danmu);
            initCommentWordCloud(data.wordCloud.comment);


            const analysisContainer = document.getElementById('analysisResult');
            analysisContainer.innerHTML = '';

            if (!data || !data.stats) {
                analysisContainer.innerHTML = '<p class="text-gray-600">没有足够的数据进行分析</p>';
                return;
            }


            const stats = data.stats;
            const viewCount = stats.view;
            const likeCount = stats.like;
            const favoriteCount = stats.favorite;
            const coinCount = stats.coin;
            const danmakuCount = stats.danmaku;
            const replyCount = stats.reply;
            const shareCount = stats.share;
            const tripleCount = stats.triple;

            const likeRate = viewCount > 0 ? (likeCount / viewCount * 100).toFixed(2) : 0;
            const favoriteRate = viewCount > 0 ? (favoriteCount / viewCount * 100).toFixed(2) : 0;
            const coinRate = viewCount > 0 ? (coinCount / viewCount * 100).toFixed(2) : 0;
            const triple = tripleCount > 0 ? (tripleCount / viewCount * 100).toFixed(2) : 0;
            const danmakuRate = viewCount > 0 ? (danmakuCount / viewCount * 100).toFixed(2) : 0;
            const replyRate = viewCount > 0 ? (replyCount / viewCount * 100).toFixed(2) : 0;
            const shareRate = viewCount > 0 ? (shareCount / viewCount * 100).toFixed(2) : 0;

            const malePercent = data.audience.gender.male;
            const femalePercent = data.audience.gender.female;

            const levelData = data.audience.level;
            let levelAnalysis = '';
            let levelDetails = [];

            const highLevelPercent = levelData.lv5 + levelData.lv6;
            const midLevelPercent = levelData.lv3 + levelData.lv4;
            const lowLevelPercent = levelData.lv0 + levelData.lv1 + levelData.lv2;

            if (highLevelPercent > 30) {
                levelAnalysis = '高等级观众占比较高，说明视频内容受到资深用户青睐';
            } else if (highLevelPercent > 15) {
                levelAnalysis = '有一定比例的高等级观众';
            } else {
                levelAnalysis = '观众等级分布以中低等级为主';
            }

            levelDetails.push(`Lv0: ${levelData.lv0}%`);
            levelDetails.push(`Lv1: ${levelData.lv1}%`);
            levelDetails.push(`Lv2: ${levelData.lv2}%`);
            levelDetails.push(`Lv3: ${levelData.lv3}%`);
            levelDetails.push(`Lv4: ${levelData.lv4}%`);
            levelDetails.push(`Lv5: ${levelData.lv5}%`);
            levelDetails.push(`Lv6: ${levelData.lv6}%`);

            let topKeywords = [];
            if (data.wordCloud.danmu && data.wordCloud.danmu.length > 0) {
                topKeywords = data.wordCloud.danmu.slice(0, 3).map(item => item.name);
            }

            const analysisReport = [
                `📊 基础数据: 播放量 ${formatNumber(viewCount)}，点赞率 ${likeRate}%，收藏率 ${favoriteRate}%，投币率 ${coinRate}%，三连率${triple}%`,
                `💬 互动质量: 弹幕量 ${formatNumber(danmakuCount)}，评论量 ${formatNumber(replyCount)}`,
                `👥 性别分布: 男 ${malePercent}%，女 ${femalePercent}%`,
                `🎚️ 等级分布: ${levelDetails.join(' | ')} ： ${levelAnalysis}`,
                `🔍 内容关键词: ${topKeywords.length > 0 ? topKeywords.join('、') : '无法提取关键词'}`,
                `${getResults(formatNumber(viewCount),formatNumber(danmakuCount),)}`
            ];

            analysisReport.forEach(item => {
                if (!item) return; // 跳过空项
                const p = document.createElement('p');
                p.className = 'text-gray-600 mb-3';
                p.innerHTML = item;
                analysisContainer.appendChild(p);
            });

            function getResults(likeRate, favoriteRate, danmakuCount, replyCount) {
                let recommendations = [];



                return recommendations.length > 0 ? recommendations.join('') : '';
            }

        } catch (error) {
            console.error('加载数据失败:', error);
            document.getElementById('basicInfoError').innerHTML = `
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4">
                <p class="font-bold">加载数据失败</p>
                <p>${error.message}</p>
            </div>
        `;
        }
    }

    // 页面加载完成后初始化数据
    window.addEventListener('load', loadAllData);
</script>
</body>
</html>